<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="公司名称" prop="companyId">
        <ApiSelect
          v-model="queryParams.companyId"
          :options="companyOptions"
          valueField="companyId"
          labelField="name"
        />
      </el-form-item>
      <el-form-item label="用户名称" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入用户名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="账号" prop="userName">
        <el-input
          maxlength="11"
          v-model="queryParams.userName"
          placeholder="请输入账号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="用户状态" clearable>
          <el-option
            v-for="dict in sys_user_stat"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="部门" prop="deptId">
        <el-tree-select
          v-model="queryParams.deptId"
          :data="departmentsOptions"
          check-strictly
          :props="CascaderProps"
          :render-after-expand="false"
          clearable
        />
      </el-form-item>
      <el-form-item label="运营城市" prop="cityName">
        <el-select @change="getList" v-model="queryParams.cityName" placeholder="请选择">
          <el-option v-for="item in cityNameOptions" :key="item" :label="item" :value="item" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="resetQuery">重置</el-button>
        <el-button type="primary" @click="handleQuery">查询</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" @click="handleAdd" v-hasPermi="['system:user:add']">
          新增
        </el-button>
      </el-col>

      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column type="index" :index="indexAdd" label="序号" width="50" align="center" />
      <el-table-column label="账号" align="center" prop="userName" />
      <el-table-column label="部门" align="center" prop="deptName" />
      <el-table-column label="名称" align="center" prop="nickName" />
      <el-table-column label="城市标签" align="center" prop="cityName" />
      <el-table-column label="邮箱" align="center" prop="email" />
      <el-table-column label="联系方式" align="center" prop="phonenumber" />
      <el-table-column label="操作人" align="center" prop="createBy" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="160" />
      <el-table-column label="用户状态" align="center" key="status" width="100">
        <template #default="{ row }">
          <dict-tag :options="sys_user_stat" :value="row.status" />
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="180" fixed="right">
        <template #default="{ row }">
          <el-button
            link
            type="primary"
            @click="handleUpdate(row)"
            v-hasPermi="['system:user:edit']"
          >
            编辑
          </el-button>
          <el-button
            v-hasPermi="['system:user:details']"
            link
            type="primary"
            @click="handleDetail(row)"
          >
            详情
          </el-button>
          <el-button
            link
            type="primary"
            v-hasPermi="['system:user:dis']"
            @click="handleStatusChange(row)"
          >
            {{ row.status == '0' ? '禁用' : '启用' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <UserDetail ref="detailRef" />
    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form :model="form" :rules="rules" ref="userRef" label-width="80px">
        <el-form-item label="公司名称" prop="companyId">
          <ApiSelect
            v-model="form.companyId"
            :options="companyOptions"
            valueField="companyId"
            labelField="name"
            :disabled="_disabled"
          />
        </el-form-item>
        <el-form-item label="账号" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入用户账号" />
        </el-form-item>

        <el-form-item label="名称" prop="nickName">
          <el-input v-model="form.nickName" placeholder="请输入名称" maxlength="30" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
        </el-form-item>

        <el-form-item label="联系方式" prop="phonenumber">
          <el-input v-model="form.phonenumber" placeholder="请输入联系方式" />
        </el-form-item>

        <el-form-item label="角色">
          <el-select v-model="form.roleIds" multiple placeholder="请选择">
            <el-option
              v-for="item in roleOptions"
              :key="item.roleId"
              :label="item.roleName"
              :value="item.roleId"
              :disabled="item.status == 1"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门" prop="deptId">
          <el-tree-select
            v-model="form.deptId"
            :data="departmentsOptions"
            check-strictly
            :props="CascaderProps"
            :render-after-expand="false"
            clearable
            @change="changeCity"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">关 闭</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="AccountUser">
import { changeUserStatus, listUser, getUser, updateUser, addUser } from '@/api/system/user'
import { encrypt } from '@/utils/jsencrypt'
import { formRules } from '@/utils/valid/formRules'
import useUserStore from '@/store/modules/user'
import UserDetail from './components/UserDetail'
import useGlobalStore from '@/store/modules/global'
import { listDept } from '@/api/system/dept'

const globalStore = useGlobalStore()
const { proxy } = getCurrentInstance()
const { sys_user_stat } = proxy.useDict('sys_user_stat')
const userStore = useUserStore()
userStore.getAllCompany()
const companyOptions = computed(() => userStore.companys)
const cityNameOptions = computed(() => globalStore.myCityList)

const detailRef = ref()
const userList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')
const dateRange = ref([])
const initPassword = ref(encrypt('888888'))
const roleOptions = ref([])
const _disabled = ref(false)
const departmentsOptions = ref([])
const CascaderProps = {
  value: 'deptId',
  label: 'deptName',
  children: 'children'
}
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userName: undefined,
    phonenumber: undefined,
    status: undefined,
    deptId: undefined,
    cityName: cityNameOptions.value[0]
  },
  rules: {
    companyId: [formRules.set('请选择公司', 'change')],
    userName: formRules.phone,
    nickName: [{ required: true, message: '用户名称不能为空', trigger: 'blur' }],
    email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }],
    phonenumber: formRules.contact,
    deptId: [{ required: true, message: '部门不能为空', trigger: 'blur' }]
  }
})

const { queryParams, form, rules } = toRefs(data)

// type序号 - 页面切换递增
function indexAdd(index) {
  const { pageNum, pageSize } = queryParams.value
  return index + 1 + (pageNum - 1) * pageSize
}

/** 查询用户列表 */
function getList() {
  loading.value = true
  listUser(queryParams.value)
    .then((res) => {
      loading.value = false
      userList.value = res.rows
      total.value = res.total
    })
    .catch(() => {
      loading.value = false
    })
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}
function getDept() {
  listDept().then((res) => {
    departmentsOptions.value = proxy.handleTree(res.data, 'deptId')
  })
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = []
  proxy.resetForm('queryRef')
  handleQuery()
}

/** 用户状态修改  */
function handleStatusChange(row) {
  let text = row.status === '1' ? '启用' : '禁用'
  proxy.$modal
    .confirm('确认要' + text + '"' + row.userName + '"用户吗?')
    .then(function () {
      return changeUserStatus(row.userId, row.status === '1' ? '0' : '1')
    })
    .then(() => {
      proxy.$modal.msgSuccess(text + '成功')
      getList()
    })
}

function handleDetail(obj) {
  detailRef.value?.init(obj)
}

/** 选择条数  */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.userId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 重置操作表单 */
function reset() {
  form.value = {
    userId: undefined,
    userName: undefined,
    nickName: undefined,
    password: undefined,
    phonenumber: undefined,
    email: undefined,
    status: '0',
    remark: undefined,
    roleIds: []
  }
  proxy.resetForm('userRef')
  _disabled.value = false
}
/** 取消按钮 */
function cancel() {
  open.value = false
  reset()
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  getUser().then((response) => {
    title.value = '添加用户'
    open.value = true
    roleOptions.value = response.roles
    form.value.password = initPassword.value
    form.value.createBy = userStore.id
    form.value.status = '0'
  })
}
function changeCity() {
  console.log(form.value.deptId)
}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const userId = row.userId || ids.value
  getUser(userId).then((response) => {
    form.value = response.data
    const isCompanyId = userStore.companys.some(
      (item) => item.companyId === response.data.companyId
    )
    if (!isCompanyId) {
      userStore.companys.push({
        name: response.data.companyName,
        companyId: response.data.companyId
      })
      _disabled.value = true
    }
    roleOptions.value = response.roles
    form.value.roleIds = response.roleIds
    open.value = true
    title.value = '修改用户'
  })
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs['userRef'].validate((valid) => {
    if (valid) {
      if (form.value.userId != undefined) {
        updateUser(form.value).then((response) => {
          proxy.$modal.msgSuccess('修改成功')
          open.value = false
          getList()
        })
      } else {
        addUser(form.value).then((response) => {
          proxy.$modal.msgSuccess('新增成功')
          open.value = false
          getList()
        })
      }
    }
  })
}
onBeforeUnmount(() => {
  useGlobalStore().getMyCityList() // 重新获取账号下的城市列表
})
getList()
getDept()
</script>

<style lang="scss" scoped>
.el-input {
  width: 215px;
}
</style>
